package com.jlf.core.mp.persistence.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlf.core.annotation.Domain;
import com.jlf.core.annotation.DomainRepository;
import com.jlf.core.domain._SimpleDO;
import com.jlf.core.mp.mapper._SimpleDao;
import com.jlf.core.mp.persistence._SimplePersistence;
import lombok.extern.slf4j.Slf4j;

import java.io.Serializable;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * 通用的自定义持久化服务
 *
 * @author wujr
 * 2020/11/19
 * @version 1.0
 * 变更历史
 * [wujr 2020/11/19 1.0 新增]
 */
@Slf4j
public abstract class _SimplePersistenceImpl<M extends _SimpleDao<T>, T extends _SimpleDO<T>> extends ServiceImpl<M, T>
        implements _SimplePersistence<T> {
    /**
     * 定义领域的缓存的路径前缀
     * @return 缓存前缀
     */
    protected String cachePrefix(){
        return null;
    }

    @Override
    public String name() {
        return baseMapper.name();
    }

    protected Domain domain() {
        return DomainRepository.annotation(this.entityClass);
    }

    @Override
    public Class<T> domainClass(){
        return this.entityClass;
    }

    protected T readOrLoad(String cacheKey, SFunction<T, ?> column, Serializable value,
                           Function<String, T> read, BiConsumer<String, T> write){
        T record = read.apply(cacheKey);
        if (null == record){
            QueryWrapper<T> wrapper = new QueryWrapper<>();
            wrapper.lambda().setEntityClass(domainClass()).eq(column, value);
            record = super.getOne(wrapper);
            if (null != record) {
                write.accept(cacheKey, record);
            }
        }
        return record;
    }
}
